<!--
 * @Author: shawnxiao
 * @Date: 2021-10-23 20:12:53
 * @LastEditTime: 2021-10-25 17:05:16
 * @FilePath: /gatt/src/modules/front/pages/GattDrag/components/GattDate/index.vue
-->
<template>
  <div class="gatt-date">
     <!-- 甘特主题内容 -->
     <gatt-main
      :allDays="allDays"
      :days="days"
      :currentDaySize="currentDaySize"
      :showFixdTopMonth="showFixdTopMonth"
      :fixdTopMonth="fixdTopMonth"
     ></gatt-main>
         <!-- 时间模式选择 -->
    <div class="gatt-date-toolTip">
      <el-dropdown trigger="click">
        <span class="base">
          {{ currentDaySize.label }}
          <i class="el-icon-arrow-down el-icon--right"></i>
        </span>
        <el-dropdown-menu
          slot="dropdown"
          :style="{ left: this.dropdownLeft + 'px !important' }"
        >
          <el-dropdown-item
            v-for="item in dayModeSize"
            :key="item.value + 'ck'"
            @click.native="handleSetDaySize(item)"
            >{{ item.label }}</el-dropdown-item
          >
        </el-dropdown-menu>
      </el-dropdown>
      <div @click="handleGoToday" class="today base" >今天</div>
    </div>
  </div>
</template>

<script>
import GattMain from './components/GattMain.vue'
export default {
  name: 'GattDate',
  components: {
    GattMain
  },
  props: {
    rightLineX: {
      type: Number,
      default: () => 300
    }
  },
  computed: {
    allDays () {
      const startTimeYear = new Date(this.startTime).getFullYear()
      const endTimeYear = new Date(this.endTime).getFullYear()
      const tmp = [startTimeYear, endTimeYear, this.currentYear - 1, this.currentYear + 1]
      // 获取到最近三年与最小年份至最大年份并集内的所有年月日
      const min = Math.min.apply(null, tmp)
      const max = Math.max.apply(null, tmp)
      let obj = {}
      const arr = []
      const tmpAllDays = []
      for (let i = min; i <= max; i++) {
        arr.push(i)
      }
      arr.forEach(item => {
        obj.year = item
        obj.days = this.isLeapYear(item) ? 365 : 366
        tmpAllDays.push(obj)
        obj = {}
      })
      // 根据年份天数创建月份及该月份下的天数数组
      tmpAllDays.forEach(item => {
        item.month = this.handleMonthDay(item.days, item.year)
      })
      tmpAllDays.forEach(element => {
        if (element.year === this.currentYear) {
          element.month[0][this.currentMonth].dayArr.forEach(k => {
            if (k.date === this.currentDay) {
              k.today = true
            }
          })
        }
      })
      console.log(tmpAllDays)
      return tmpAllDays
    },
    // 所有的天数
    days () {
      let arrTmp = []
      let arr = []
      this.allDays.forEach(element => {
        arrTmp = arrTmp.concat(element.month)
      })
      arrTmp.forEach(item => {
        for (var j in item) {
          arr = arr.concat(item[j].dayArr)
        }
      })
      arr.forEach((item, index) => {
        item.width = (index + 1) * this.currentDaySize.value
      })
      return arr
    },
    dropdownLeft () {
      return window.innerWidth - 30
    },
    // 当前年份
    currentYear () {
      return new Date().getFullYear()
    },
    // 当前月份
    currentMonth () {
      return new Date().getMonth() + 1
    },
    // 当前日
    currentDay () {
      return new Date().getDate()
    }
  },
  data () {
    return {
      // 整体开始时间
      startTime: 1600473600000,
      // 整体结束时间
      endTime: 1600473600000,
      // 近三年的所有年月日(开始至结束时间与近三年的并集)
      // allDays: [],
      // 所有的天数
      // days: [],
      // 月数
      monthArr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
      // 当前的时间大小
      currentDaySize: {
        label: '按天',
        value: 40,
        mode: 'day'
      },
      dayModeSize: [
        {
          label: '按天',
          value: 40,
          mode: 'day'
        },
        {
          label: '按周',
          value: 18,
          mode: 'week'
        },
        {
          label: '月度',
          value: 8,
          mode: 'month'
        },
        {
          label: '季度',
          value: 4,
          mode: 'quarter'
        },
        {
          label: '半年',
          value: 1,
          mode: 'halfYear'
        }
      ],
      showFixdTopMonth: false,
      fixdTopMonth: ''
    }
  },
  methods: {
    // 根据距离计算时间
    /**
     * @param  {Number} width
     * @param  {Boolean|String} time
     */
    computedWithTime (width, time) {
      const startTimeYear = new Date(this.startTime).getFullYear()
      let startYear = 0
      if (this.currentYear - 1 > startTimeYear) {
        startYear = startTimeYear
      } else {
        startYear = this.currentYear - 1
      }
      const startTime =
        (width / this.currentDaySize.value) * (1000 * 60 * 60 * 24) +
        new Date(`${startYear}/01/01`).getTime()
      const s = new Date(startTime)
      if (time && time === true) {
        return s.getTime()
      } else if (time && time === 'YD') {
        let m = s.getMonth() + 1
        m = m < 10 ? `0${m}` : m
        return `${s.getFullYear()}/${m}`
      } else {
        let m = s.getMonth() + 1
        m = m < 10 ? `0${m}` : m
        let d = s.getDate()
        d = d < 10 ? `0${d}` : d
        return `${s.getFullYear()}/${m}/${d}`
      }
    },
    // 更改daySize
    handleSetDaySize (item) {
      this.currentDaySize = item
      this.days.forEach((item, index) => {
        item.width = (index + 1) * this.currentDaySize.value
      })
      this.handleScroll()
      if (this.currentRow) {
        const rs = this.computedList.find(o => {
          return o.id === this.currentRow.id
        })
        this.$nextTick(() => {
          window.scrollTo(rs.left - 100, 0)
        })
      }
    },
    // 回到今天
    handleGoToday () {
      const s =
        Math.round(window.innerWidth / this.currentDaySize.value / 2) *
          this.currentDaySize.value -
        this.rightLineX
      const width =
        (Math.floor(
          new Date(
            `${this.currentYear}/${this.currentMonth}/${this.currentDay}`
          ).getTime() - new Date(`${this.currentYear - 1}/01/01`).getTime()
        ) /
          (1000 * 60 * 60 * 24)) *
          this.currentDaySize.value -
        s
      window.scrollTo({
        top: 0,
        left: width,
        behavior: 'smooth'
      })
    },
    /**
     * @description 获取该月下所有的天和周的数据情况
     * @param  {Number} days 该年下天数总计
     * @param  {Number} year
     */
    handleMonthDay (days, year) {
      const arr = []
      const obj = {}
      this.monthArr.forEach(item => {
        obj[item] = {
          dayArr: [],
          weekArr: []
        }
        let ob = {}
        // 该月的天数总计
        ob.totalDay = this.checkMonthDays(item, days)
        obj[item].dayArr.push(ob)
        ob = {}
      })
      arr.push(obj)
      const s = arr[0]
      for (const item in s) {
        const num = s[item].dayArr[0].totalDay
        const tempArr = this.getWeekDateByMounth(num, item, year)
        tempArr.forEach(keyItem => {
          if (keyItem.weekday === 1) {
            s[item].weekArr.push(keyItem.date)
          }
        })
        s[item].dayArr = []
        s[item].dayArr = tempArr
      }
      return arr
    },
    /**
     * @description 获取月份下所有天的日期和星期几
     * @param  {number} num 天数
     * @param  {number} month 月份
     * @param  {number} year 年份
     */
    getWeekDateByMounth (num, month, year) {
      const arr = []
      let obj = {}
      const quarterArr = [1, 4, 7, 10]
      const halfYearArr = [1, 7]
      for (let i = 1; i <= num; i++) {
        if (quarterArr.includes(~~month) && i === 1) {
          // 季度开始日/分割线
          obj.quarterStrat = true
        }
        if (halfYearArr.includes(~~month) && i === 1) {
          // 半年开始日/分割线
          obj.halfYearStrat = true
        }
        obj.year = year
        obj.month = ~~month
        obj.date = i
        obj.weekday = new Date(`${year}/ ${month} / ${i}`).getDay()
        arr.push(obj)
        obj = {}
      }
      return arr
    },
    // 根据月份返回天数
    /**
     * @param  {Number} month 月份
     * @param  {Number} days 天数
     */
    checkMonthDays (month, days) {
      let day
      switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
          return 31
          // eslint-disable-next-line no-unreachable
          break
        case 4:
        case 6:
        case 9:
        case 11:
          return 30
          // eslint-disable-next-line no-unreachable
          break
        case 2:
          day = days === 365 ? 28 : 29
          return day
          // eslint-disable-next-line no-unreachable
          break
      }
    },
    // 判断是否为闰年
    /**
     * @param  {Number} year 传入年份
     */
    isLeapYear (year) {
      return year % 4 > 0
    },
    // 顶部固定时间
    handleScroll () {
      const w = window.scrollX
      if (w <= 62) {
        this.showFixdTopMonth = false
      } else {
        this.showFixdTopMonth = true
      }
      const time = this.computedWithTime(w, 'YD')
      this.fixdTopMonth = time
    }
  },
  mounted () {
    document.addEventListener('scroll', this.handleScroll)
  },
  beforeDestroy () {
    window.removeEventListener('scroll', this.handleScroll)
    document.onmousemove = document.onmouseup = null
  }
}
</script>

<style lang="stylus" scoped>
.gatt-date{
  width: 100%;
  height: 100%;
    &-toolTip{
    position: fixed;
    right: 0px;
    top: 82px;
    z-index: 999;
    .base{
      display: inline-block;
      text-align: center;
      height: 30px;
      line-height: 30px;
      padding: 0 15px;
      background-color: #fff;
      font-size: 14px;
      cursor: pointer;
      user-select: none;
      transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
      font-weight: 400;
      color: #303030;
      border-radius: 3px;
      box-shadow: 0 3px 12px 0 rgba(48, 48, 48, 0.05),
        0 3px 6px 0 rgba(48, 48, 48, 0.1);
      margin-right: 20px;
      &:hover{
        color: #409eff;
      }
    }
  }
}
</style>
